#![allow(dead_code)]

use crate::entity::{
    prelude::*,
    stock_wallet::{self, *},
};
use sea_orm::{prelude::*, query::*, *};

#[derive(Debug, Default)]
pub struct WalletSearch {
    uid: Option<i32>,
    stock_code: Option<String>,
    status: Option<i32>,
    pageindex: u64,
    pagesize: u64,
}

pub async fn get_by_stockcode(
    db: &DbConn,
    uid: i32,
    stock_code: String,
) -> Result<Option<Model>, DbErr> {
    StockWallet::find()
        .filter(stock_wallet::Column::Uid.eq(uid))
        .filter(stock_wallet::Column::StockCode.eq(stock_code))
        .one(db)
        .await
}
pub async fn update_number_by_trade_newday(db: &DbConn) -> Result<ExecResult, DbErr> {
    db.execute_unprepared("UPDATE stock_wallet SET usable_number = usable_number + disable_number,disable_number = 0;").await
}
pub async fn update_number_by_trade(
    db: &DbConn,
    uid: i32,
    stock_code: String,
    number: i32,
) -> Result<Model, DbErr> {
    let res = get_by_stockcode(db, uid, stock_code).await?;
    let model = res.unwrap();
    let mut entity = model.clone().into_active_model();

    entity.disable_number = Set(model.disable_number - number);
    entity.usable_number = Set(model.usable_number + number);
    entity.update(db).await
}
pub async fn update_number_by_trade_success(
    db: &DbConn,
    uid: i32,
    stock_code: String,
    number: i32,
) -> Result<Model, DbErr> {
    let res = get_by_stockcode(db, uid, stock_code.clone()).await?;

    if res.is_none() {
        let model = stock_wallet::Model {
            uid: uid,
            stock_code: stock_code.clone(),
            id: 0,
            disable_number: number.abs(),
            usable_number: 0,
        };
        let add_res = add(db, model.clone()).await;
        if add_res.is_err() {
            return Err(DbErr::Custom("添加异常".to_owned()));
        }
        return Ok(model);
    }
    let model = res.unwrap();
    let mut entity = model.clone().into_active_model();
    entity.disable_number = Set(model.disable_number + number);
    entity.update(db).await
}

pub async fn get_page(db: &DbConn, search: WalletSearch) -> Result<(Vec<Model>, u64), DbErr> {
    let mut query: Select<StockWallet> = StockWallet::find();

    query = match search.uid {
        Some(value) => query.filter(Column::Id.eq(value)),
        None => query,
    };

    query = match search.stock_code {
        Some(value) => query.filter(Column::StockCode.contains(&value)),
        None => query,
    };

    let page: Paginator<DatabaseConnection, SelectModel<Model>> = query
        .order_by_desc(Column::Uid)
        .paginate(db, search.pagesize);

    let num_pages = page.num_pages().await?;
    page.fetch_page(search.pageindex - 1)
        .await
        .map(|p| (p, num_pages))
}

pub async fn add(db: &DbConn, model: Model) -> Result<InsertResult<ActiveModel>, DbErr> {
    let entity: ActiveModel = model.into();
    StockWallet::insert(entity).exec(db).await
}

pub async fn delete(db: &DbConn, id: i32) -> Result<DeleteResult, DbErr> {
    StockWallet::delete_by_id(id).exec(db).await
}
